<!--
 * @Descripttion: 商品详情
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-10 15:18:53
 -->
<template>
  <div class="app-container paddingT50">
    <affix>
      <div class="paddingLR20 clearfix">
        <el-card shadow="never" class="oper-btn-card">
          <div class="clearfix">
            <el-button type="primary" size="medium" class="fl" :loading="btnLoading.save" @click="btnSave">保 存</el-button>
            <el-button type="default" size="medium" class="fl" @click="btnCancle">取 消</el-button>
          </div>
        </el-card>
      </div>
    </affix>
    <!-- skuDetailData: {{ skuDetailData }} -->
    <el-card shadow="never" class="border-radius-none margin-t2">
      <good-base ref="goodBase" :oper="oper" />
      <good-unit ref="goodUnit" :base-data="baseData" :oper="oper" class="margin-t20" />
      <good-specs
        ref="goodSpecs"
        :sku-specs-data="skuSpecsData"
        class="margin-t40"
      />
      <div class="margin-t20">
        <sku-more
          ref="skuMore"
          :sku-data="currentSkuData"
          :unit-data="unitData"
          :store-data="storeData"
        />
      </div>
    </el-card>
  </div>
</template>
<script>
import { saveData } from '@/api/goods/goods-sku.js'
import { oftenuse } from '@/libs/mixins'
import clonedeep from 'clonedeep'
import { BaseSku as GoodBase, SpecsSku as GoodSpecs, Unit as GoodUnit } from './components'
import Affix from '@/components/Affix'
import SkuMore from './sku-more'
import { getStoreAllOptions as getStoreOptions } from '@/api/bsd/store.js'
import store from '@/store'
import { getSkuDetailById } from '@/api/goods/goods-sku.js'
import { getPriceList, getBarcodeList } from './tools.js'

export default {
  name: 'SkuEdit',
  components: { GoodBase, GoodSpecs, GoodUnit, SkuMore, Affix },
  mixins: [oftenuse],
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    skuid: {
      type: String,
      required: true
    },
    oper: {
      type: String,
      default: 'edit'
    }
  },
  data() {
    return {
      comps: {}, // 组件
      isShowDrawer: false,
      currentSkuData: null,
      skuDetailData: {}, // sku详情
      skuSpecsData: {}, // sku的规格数据
      storeData: [],
      priceTypes: store.getters.appData.configs.priceTypes
    }
  },
  computed: {
    /**
     * 基础数据
     */
    baseData: function() {
      const goodBaseComp = this.comps.goodBase
      if (!goodBaseComp) return {}
      return clonedeep(goodBaseComp.dataObj)
    },
    /**
     * 单位post数据
     */
    unitData: function() {
      const goodUnitComp = this.comps.goodUnit
      if (!goodUnitComp) return []
      else return goodUnitComp.getGoodUnitData()
    },
    specsDataStr: function() {
      const specsComp = this.comps.goodSpecs
      if (!specsComp) return ''
      const specsDataStr = specsComp.getSpecsData()
      const isEnableSpecs = specsComp.getIsEnableSpecs()
      if (isEnableSpecs === '1') {
        const specsData = JSON.parse(specsDataStr)
        let str = ''
        Object.keys(specsData).forEach(key => {
          const val = specsData[key]
          if (val) str = str + '-' + val
        })
        return str
      }
      return `-${specsDataStr}`
    }
  },
  watch: {
  },
  created() {
    this.initData()
  },
  destroyed() {
  },
  updated() {
    this.setComponents()
  },
  mounted() {
    this.setComponents()
  },
  methods: {
    btnGetPostData() {
    },
    btnDrawerSure() {
      this.isShowDrawer = false
    },
    btnCancle() {
      this.jump2list()
    },
    btnSave(oper) {
      this.valiData().then(res => {
        const goodsSpu = this.comps.goodBase.getData()
        const { id, code, name, catId, catName, spuId } = goodsSpu
        const isEnableSpecs = this.comps.goodSpecs.getIsEnableSpecs()
        const skuData = { id, code, name, catId, catName, isEnableSpecs, spuId }
        const specsData = this.comps.goodSpecs.getSpecsData()
        const unitData = this.comps.goodUnit.getGoodUnitData()
        const skuMoreData = this.$refs.skuMore.getData()
        // 数据处理
        skuData.specs = specsData
        unitData.forEach(item => {
          item.unitId = item.value
          item.unitName = item.label
        })
        const { priceData, barcodeData, stockData, stockWarnData } = skuMoreData
        debugger
        const params = {
          goodsSku: skuData,
          goodsPriceList: priceData,
          goodsUnitList: unitData,
          goodsBarcodeList: barcodeData,
          goodsStockList: stockData,
          goodsStockWarnList: stockWarnData
        }
        this.setBtnLoading('save', true)
        this.saveGoodData(params).then(res => {
          this.setBtnLoading('save', false)
        })
      })
    },
    jump2list() {
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'GoodsList',
        params: { refresh: true }
      })
    },
    saveGoodData(params) {
      return new Promise((resolve, reject) => {
        saveData(params).then(res => {
          resolve(res)
          const title = res.data.title || '保存成功！'
          if (!res.data.flag) return
          this.$notify.success({ title })
          this.jump2list()
        }).catch(err => {
          reject(err)
        })
      })
    },
    valiData(callback) {
      const goodBaseComp = this.comps.goodBase
      const goodUnitComp = this.comps.goodUnit
      const goodSpecsComp = this.comps.goodSpecs
      const v1 = goodBaseComp.handleValid('goodBase')
      const v2 = new Promise((resolve, reject) => {
        if (!goodUnitComp) resolve()
        goodUnitComp.handleValid('goodUnit').then(_ => {
          resolve()
        }).catch(_ => {
          reject()
        })
      })
      const v3 = new Promise((resolve, reject) => {
        if (!goodSpecsComp) resolve()
        goodSpecsComp.valiData().then(_ => {
          resolve()
        }).catch(_ => {
          reject()
        })
      })
      return Promise.all([v1, v2, v3])
    },
    resetData() {
      const goodBaseComp = this.$refs.goodBase
      goodBaseComp.resetData()
    },
    setComponents: function() {
      this.$set(this.comps, 'goodBase', this.$refs.goodBase)
      this.$set(this.comps, 'goodUnit', this.$refs.goodUnit)
      this.$set(this.comps, 'goodSpecs', this.$refs.goodSpecs)
    },
    initData() {
      this.initStoreData()
      this.initSkuData()
    },
    initStoreData() {
      getStoreOptions().then(res => {
        const data = res.data.data
        this.storeData = data
      })
    },
    initSkuData() {
      const skuid = this.skuid
      getSkuDetailById(skuid).then(res => {
        if (!res.data.flag) return
        const data = res.data.data || []
        if (this.oper === 'copyadd') {
          this.$delete(data.goodssku, 'id')
        }
        this.skuDetailData = data
        this.handleSkuDetailData(data)
      })
    },
    handleSkuDetailData(skuDetailData) {
      const { goodssku, skuInfoDtoList } = skuDetailData
      const goodsStockList = skuInfoDtoList
      // ## 基础信息 ##
      this.comps.goodBase.setData(goodssku)
      // ## 单位信息 ##
      const { unitId, unitMulti, unitName, isBaseUnit } = goodssku
      const isBaseUnitArr = isBaseUnit.split(',')
      const unitIdArr = unitId.split(',')
      const unitNameArr = unitName.split(',')
      const unitMultiArr = unitMulti.split(',')
      // 基础单位的index
      const baseIndex = isBaseUnitArr.findIndex(item => { return item === '1' })
      let unitBase = null
      const viceUnit = []
      for (let i = 0; i < unitIdArr.length; i++) {
        if (i === baseIndex) {
          unitBase = unitIdArr[baseIndex]
        } else {
          const obj = {
            value: unitIdArr[i],
            label: unitNameArr[i],
            isBase: isBaseUnitArr[i],
            multi: unitMultiArr[i]
          }
          viceUnit.push(obj)
        }
      }
      this.comps.goodUnit.setData({ unitBase, viceUnit })
      // 规格
      const isEnableSpecs = goodssku.isEnableSpecs
      const specsValueData = goodssku.specs
      this.skuSpecsData = { isEnableSpecs, specsValueData }
      // skuMore
      const goodspriceList = getPriceList(goodssku)
      const goodsBarcodeList = getBarcodeList(goodssku)
      goodsStockList.forEach(item => {
        const { originQuantity, originCostPrice } = item
        item.costPrice = originCostPrice
        item.costTotalPrice = this.$amount(originQuantity).multiply(originCostPrice)
      })
      const goodsStockWarnList = goodsStockList
      const skuData = { goodspriceList, goodsBarcodeList, goodsStockList, goodsStockWarnList }
      this.currentSkuData = clonedeep(skuData)
    }
  }
}
</script>

<style scoped>
</style>
